package callgraph;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * traditional representation of a graph/relation
 * 
 */
public class AdjacencyMatrix {
	
	Identities ids = new Identities();
	/*****************************************
	 * semantics: call[i][j] == true iff 
	 * execution of method A may invoke method B. 
	 *****************************************/
	private boolean[][] matrix;

	public AdjacencyMatrix(int numMethods) {
		matrix = new boolean[numMethods][numMethods];
	}
	
	public void set(int i, int j) {
		matrix[i][j] = true;
	}
	
	public int[] getCallees(int i) {
		ArrayList<Integer> callees = new ArrayList<Integer>();
		for (int j = 0; j < matrix.length; j++) {
			if (matrix[i][j]) {
				callees.add(j);
			}
		}
		/*****************************************************
		 * this is just to avoid dependency on java.util.List
		 *****************************************************/
		int k = 0;
		int[] result = new int[callees.size()];
		for (Integer val : callees) {
			result[k++] = val;
		}
		return result;
	}
	
	public void update(String parent, List<String> children) {
		int idParent = ids.getID(parent);
		for (String child : children) {
			set(idParent, ids.getID(child));
		}
	}
	
	public String toString() {
		StringBuffer sb = new StringBuffer();
		for (String name : ids.getKeys()) {
			int id = ids.getID(name);
			sb.append("**** " + id + ": " + name+"\n");
			sb.append(Arrays.toString(getCallees(id))+"\n");
		}
		return sb.toString();
	}

}